package cn.bone.mqtt.demo02;

import cn.bone.mqtt.demo01.PushCallback;
import com.alibaba.fastjson.JSON;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * Created by MD-01 on 2017/4/19.
 */
public class Server {

    private static Logger logger = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) throws MqttException, UnsupportedEncodingException {

        String host = "tcp://127.0.0.1:1883";
        //String host = "tcp://127.0.0.1:61613";
        String clientId = "demo02/server";
        MqttClient client = new MqttClient(host,clientId,new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName("admin");
        options.setPassword("password".toCharArray());
        //options.setWill("server02Will","server over".getBytes(),2,true);

        client.setCallback(new MyCallBack(client,100));
        client.connect(options);
        MqttMessage message = new MqttMessage();
        //message.setId(100);
        message.setQos(2);
        message.setRetained(true);
        message.setPayload("发送给client02的消息_6".getBytes("UTF-8"));
        MqttTopic topic = client.getTopic("demo02/client");
        MqttDeliveryToken token = topic.publish(message);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                logger.info("onSuccess");
                MqttWireMessage response = asyncActionToken.getResponse();
                logger.info(JSON.toJSONString(response));
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                logger.info("onFailure");
                logger.info(exception.getMessage());
            }
        });
        new Thread(new ServerThread(client,options)).start();
    }
}
